import {ref } from "vue";

class EDSWebSocket{
    currMsg = ref("")
    messages = ref([])
    messageHandlers = []
    constructor(url){
        this.url = url;
        this.ws = null;
    }

    connect(url,options={}){
        this.url=url
        this.options=options
        if (this.ws==null){
            this.ws=new WebSocket(this.url);
            this.ws.onmessage=function(event){
                onmessage(event.data)
            }
            let collectMessage=function onmessage(data){
                this.messageHandlers.forEach(messageHandler=> {
                    messageHandler(data)
                });
            }
            let onmessage = collectMessage.bind(this)

            this.ws.onerror=function(event){
                console.log(event)
            }
            this.ws.onclose=function(event){
                console.log("websocket with "+this.url+" has been closed "+event.code)
            }
        }
    }

    addMessageHandler(method){
        this.messageHandlers.push(method)
    }
    
    send(data){
        if(this.ws.readyState===WebSocket.OPEN){
            this.ws.send(data)
        }else{
            console.error("websocket connection not open")
        }
    }

    // getMessages(){
    //     return this.messages
    // }

    close(){
        this.ws.close()
    }
}

export default EDSWebSocket